﻿#region License information
/*
 * Smart Include
 *  
 * Copyright (c) 2014 Fredrik Schultz
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 * 
 * Project website: http://kaliko.com/smart-include/
 */
#endregion

namespace Kaliko.SmartInclude {
    using System;
    using System.ComponentModel;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    /// <summary>
    /// Use this WebControl to gather all the uncompressed scripts you want to be placed 
    /// into one single script file, minified, compressed and included on your page.
    /// </summary>
    public class IncludeScript : WebControl, INamingContainer {
        [Browsable(false), 
         DefaultValue(null), 
         PersistenceMode(PersistenceMode.InnerProperty)]
        public string Url { get; set; }

        [Browsable(false),
         DefaultValue("Default"),
         PersistenceMode(PersistenceMode.InnerProperty)]
        public string Group { get; set; }

        /// <summary>
        /// Overriden. This function runs once this control is added and calls AddScriptToCue
        /// in order to register the script file to include.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e) {
            AddScriptToCue();

            base.OnLoad(e);
        }

        /// <summary>
        /// Adds the script path defined in the Url property to the list of files to include,
        /// but ONLY if it doesn't already appear (to prevent duplicate includes).
        /// </summary>
        private void AddScriptToCue() {
            var key = string.Format("ScriptIncludes_{0}", Group);
            var includeCollection = IncludeCollection.GetCollection(key);

            if (includeCollection.Includes.Contains(Url)) {
                return;
            }

            includeCollection.Includes.Add(Url);
            includeCollection.Save();
        }

        /// <summary>
        /// This function renders the script include tag to the page at the same 
        /// place you first called this WebControl for the specified group.
        /// 
        /// If Config.Debug is set to true (which is done in the web.config file) 
        /// instead of getting an include to the compressed and one-filed scripts 
        /// each script is generated in it's original uncompressed form to help 
        /// you out while debugging your scripts.
        /// </summary>
        /// <param name="writer"></param>
        protected override void Render(HtmlTextWriter writer) {
            if (Config.DebugMode) {
                writer.Write("<script src=\"{0}\" type=\"text/javascript\"></script>", Url);
            }
            else {
                var key = string.Format("ScriptIncludes_{0}", Group);
                var includeCollection = IncludeCollection.GetCollection(key);

                if (!includeCollection.IsRendered) {
                    writer.Write(JavascriptMinifier.MinifyScripts(includeCollection.Includes));
                    includeCollection.IsRendered = true;
                    includeCollection.Save();
                }
            }
        }
    }
}